package com.team06.util;
import com.team06.pojo.Arre;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ArreXmlParserUtil {
    private static final Logger LOGGER = Logger.getLogger(ArreXmlParserUtil.class.getName());

    public static Arre parseXml(String xmlPath) {
        Arre entity = new Arre();
        try {
            File file = new File(xmlPath);
            SAXBuilder saxBuilder = new SAXBuilder();
            Document document = saxBuilder.build(file);
            Element root = document.getRootElement();

            // 解析 META 节点
            Element metaElement = root.getChild("META");
            if (metaElement != null) {
                entity.setSender(metaElement.getChildText("SNDR"));
                entity.setReceiver(metaElement.getChildText("RCVR"));
                entity.setSequence(Integer.parseInt(metaElement.getChildText("SEQN")));
                entity.setDtime(metaElement.getChildText("DDTM"));
                entity.setMtype(metaElement.getChildText("TYPE"));
                entity.setStype(metaElement.getChildText("STYP"));
            }

            // 解析 DFLT 节点
            Element dfltElement = root.getChild("DFLT");
            if (dfltElement != null) {
                entity.setDfltFlid(Integer.parseInt(dfltElement.getChildText("FLID")));
                entity.setDfltFatt(dfltElement.getChildText("FATT"));
                entity.setDfltFfid(dfltElement.getChildText("FFID"));
                entity.setDfltFide(dfltElement.getChildText("FIDE"));
                entity.setDfltStat(dfltElement.getChildText("STAT"));
                entity.setDfltIsta(dfltElement.getChildText("ISTA"));
                entity.setDfltMsta(dfltElement.getChildText("MSTA"));
                entity.setDfltMist(dfltElement.getChildText("MIST"));
                entity.setDfltFrlt(dfltElement.getChildText("FRLT"));
            }
        } catch (JDOMException | IOException | NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Failed to parse XML file: " + xmlPath, e);
            return null;
        }
        return entity;
    }
}